package com.bcfn.bshop.common.utils;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @author LiangGuoNing
 * @create 2019年2月9日 上午11:09:05
 * @copyright
 * @modify
 */
public class HttpClientUtils {

	//private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日志记录

    private static RequestConfig requestConfig = null;

    static
    {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
    }
    
    
    /**
     * 发送get请求
     * @param url 路径
     * @return
     */
    public static String httpGet(String url){
	    // get请求返回结果
	    //JSONObject jsonResult = null;
	    StringBuilder result = new StringBuilder();
	    CloseableHttpClient client = HttpClients.createDefault();
	    // 发送get请求
	    HttpGet request = new HttpGet(url);
	    request.setConfig(requestConfig);
	    try
	    {
	        CloseableHttpResponse response = client.execute(request);
	
	        // 请求发送成功，并得到响应
	        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
	        {
	            // 读取服务器返回过来的json字符串数据
	            HttpEntity entity = response.getEntity();
	            //String strResult = EntityUtils.toString(entity, "utf-8");
	            result.append(EntityUtils.toString(entity, "utf-8"));
	            // 把json字符串转换成json对象
	            //jsonResult = JSONObject.parseObject(strResult);
	        }
	        else
	        {
	            System.out.println("get请求提交失败:" + url);
	        }
	    }
	    catch (IOException e)
	    {
	    	System.out.println("get请求提交失败:" + url + e);
	    }
	    finally
	    {
	        request.releaseConnection();
	    }
	    return result.toString();
    }
    
    /**
     * 
     * @param url
     * @param clazz
     * @return
     */
    public static <T> T httpGet(String url,Class<T> clazz) {
    	T result = null;
    	String jsonStr = httpGet(url);
    	//JSONObject jsonResult = JSONObject.parseObject(json);
    	//t = jsonResult.toJavaObject(clazz);
    	result = JSONObject.parseObject(jsonStr, clazz);
    	return result;
    }
    
    /**
     * post请求传输String参数 例如：name=Jack&sex=1&type=2
     * Content-type:application/x-www-form-urlencoded
     * @param url            url地址
     * @param strParam       参数
     * @return
     */
    public static String httpPost(String url,Object strParam){
    	 String jsonStr = null;
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try
        {
            if (null != strParam)
            {
                // 解决中文乱码问题
            	String json = JSONObject.toJSONString(strParam);
                StringEntity entity = new StringEntity(json, "utf-8");
                entity.setContentEncoding("UTF-8");
                //entity.setContentType("application/x-www-form-urlencoded");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                try
                {
                    // 读取服务器返回过来的json字符串数据
                	jsonStr = EntityUtils.toString(result.getEntity(), "utf-8");
                }
                catch (Exception e)
                {
                	System.out.println("post请求提交失败:" + url + e);
                }
            }
        }
        catch (Exception e)
        {
        	System.out.println("post请求提交失败:" + url + e);
        }
        finally
        {
            httpPost.releaseConnection();
        }
        return jsonStr;
    }
    
    public static <T> T httpPost(String url,Object param,Class<T> clazz) {
    	T result = null;
    	String jsonStr = httpPost(url,param);
    	result = JSONObject.parseObject(jsonStr, clazz);
    	return result;
    }
}
